# -*- coding: utf-8 -*-
"""
Author:duan
Date: 2021/2/27 15:21
"""
# 发布订阅模式
# 订阅者
import pika

credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', credentials=credentials))
channel = connection.channel()
channel.exchange_declare(exchange='ex1', exchange_type='fanout')
# 声明一个名为ex1的交换器，发布类型为集体分发
result = channel.queue_declare(queue='', exclusive=True)
# 这里不定义名字，通过exclusive=True生成一个名字不重复的队列
queue_name = result.method.queue
# 获取队列名
channel.queue_bind(queue_name, exchange='ex1')
# 绑定队列名和ex1交换器
def callback(ch, method, properties, body):
    print("Received msg: {}".format(body))

channel.basic_consume(queue_name, callback, True)
# 使用随机生成的队列名在ex1交换器下接收消息
print('queue:{} start...'.format(queue_name))
channel.start_consuming()
